const path = require('path');
const Mock = require('mockjs');
const express = require('express');
const chokidar = require('chokidar');
const chalk = require('chalk');
const mockDir = path.join(process.cwd(), 'mock');

// 注册接口路由
function registerRoutes(app, i = false) {
  const mockArr = require('./index');
  const mockServer = mockArr.map(route => responseFake(route));
  mockServer.forEach(e => app[e.type](e.url, e.response));
  const index = app._router.stack.length - mockServer.length;
  const length = mockServer.length;
  // 放到上一次加载的位置，避免路由被通配符路由拦截
  if (i) {
    app._router.stack.splice(i, 0, ...app._router.stack.splice(index, length));
    return { length, index: i }
  }
  return { length, index }
}
// 格式化接口数据
function responseFake({ type, url, response }) {
  return {
    url: new RegExp(`${process.env.VUE_APP_BASE_API}${url}`),
    type: type || 'get',
    response(req, res) {
      console.log(chalk.green('request invoke:' + req.path))
      res.json(Mock.mock(response instanceof Function ? response(req, res) : response))
    }
  }
}
// 卸载路由 
function unregisterRoutes() {
  Object.keys(require.cache).forEach(i => {
    if (i.includes(mockDir)) {
      delete require.cache[require.resolve(i)]
    }
  })
}
module.exports = (app) => {
  app.use(express.json());
  app.use(express.urlencoded({ extended: false }));

  const mockRoutes = registerRoutes(app);
  var length = mockRoutes.length;
  var index = mockRoutes.index;
  chokidar.watch(mockDir, {
    ignored: /server\.js/,
    ignoreInitial: true
  }).on('all', (event, path) => {
    try {
      console.log(chalk.hex('#f60')('>', event, path));
      app._router.stack.splice(index, length);
      unregisterRoutes();
      const mockRoutes = registerRoutes(app, index);
      length = mockRoutes.length;
      index = mockRoutes.index;
    } catch (error) {
      console.log(chalk.red(error));
    }
  })
}

